import {CookieUtil} from "./CookieUtil";


export class HttpUtil {

    static get(url,params){

        if (params) {
            let paramsArray = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }

        return fetch(url,{
            method:"get",
            headers:{
                "Content-type":"application/x-www-form-urlencoded",
                "Authorization": 'Basic ' + CookieUtil.readCookie('token'),
            }
        }).then(function (response){
            if (response.status === 200 || response.status === 201){
                return response;
            }else if(response.status === 401){
                return 401;
            }
        }).then(function (data) {
            return data ? data.text() : data;
        }).catch(function (res) {
            console.log('got an error when fetch');
        })
    }

    static post(url,param){

        return fetch(url,{
            method:"post",
            headers:{
                //"Content-type":"application/x-www-form-urlencoded",
                "Content-type":"application/json",
                "Authorization": 'Basic ' + CookieUtil.readCookie('token'),
            },
            body : JSON.stringify(param)
        }).then(function (response){
            if (response.status === 200 || response.status === 201){
                return response;
            }else if(response.status === 401){
                return 401;
            }
        }).then(function (data) {
            return data.text();
        })
    }

    static upload(url,param){

        return fetch(url,{
            method:"post",
            body : param
        }).then(function (response){
            if (response.status === 200){
                return response;
            }else if(response.status === 401){
                return 401;
            }
        }).then(function (data) {
            return data.text();
        })
    }

}